#include <assert.h>

#include "ctnode.h"

void ctlist_create (CTList *list)
{
  list->head = NULL;
  list->tail = NULL;
}

void ctlist_forall (CTList *list, ctnode_callback callback, void *data)
{
  CTNode *node = list->head;
  CTNode *next;

  while (node != NULL) {
    /* Save the next node before calling callback in case
     * callback frees the node */
    next = node->next;
    callback (node, data);
    node = next;
  }
}

void ctlist_append_node (CTList *list, CTNode *node)
{
  if (list->head == NULL)
    list->head = node;
  else
    list->tail->next = node;

  node->next = NULL;
  list->tail = node;
}

void ctlist_prepend_node (CTList *list, CTNode *node)
{
  if (list->head == NULL)
    list->tail = node;

  node->next = list->head;
  list->head = node;
}

void ctlist_remove_node (CTList *list, CTNode *node)
{
  CTNode *cond = list->head;
  CTNode *prev = NULL;

  while (cond != NULL && cond != node) {
    prev = cond;
    cond = cond->next;
  }

  if (cond == node) {
    if (cond == list->head)
      list->head = cond->next;
    else if (cond == list->tail)
      list->tail = prev;
    else
      prev->next = cond->next;

    cond->next = NULL;
  }
}
